/** @Date 上午11:53:28
  * @version 1.0.0
  * @author shangyd
  * Copyright (c) 2015
  */
package com.sdw.soft.test.zookeeper;

import java.util.List;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.IZkStateListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZkClientDemo {

	private static final Logger logger = LoggerFactory.getLogger(ZkClientDemo.class);
	
	private static final String SERVERLIST = "192.168.183.133";
	private static ZkClient zkClient = null;
	private String path = "/root";
	
	@Before
	public void test00(){
		zkClient = new ZkClient(SERVERLIST);
		zkClient.subscribeChildChanges(path, new IZkChildListener() {
			
			@Override
			public void handleChildChange(String parentPath, List<String> currentChilds)
					throws Exception {
				logger.info("child change : at parentPath="+ parentPath + ",currentChilds=" + currentChilds);
			}
		});
		zkClient.subscribeDataChanges(path, new IZkDataListener() {
			
			@Override
			public void handleDataDeleted(String dataPath) throws Exception {
				logger.info("zookeeper node deleted at " + dataPath);
			}
			
			@Override
			public void handleDataChange(String dataPath, Object data) throws Exception {
				logger.info("zookeeper node has changed at " + dataPath + ",data is " + data.toString());
			}
		});
		
		zkClient.subscribeStateChanges(new IZkStateListener() {
			
			@Override
			public void handleStateChanged(KeeperState state) throws Exception {
				logger.info("handle  state changed ---" + state.name());
			}
			
			@Override
			public void handleNewSession() throws Exception {
				logger.info("handle new session !!!");
			}
		});
	}
	
	@Test
	public void test01(){
		zkClient.createPersistent(path);
		zkClient.create(path + "/child", "child node", CreateMode.EPHEMERAL);
		List<String> children = zkClient.getChildren(path);
		int childCount = zkClient.countChildren(path);
		zkClient.exists(path);
		zkClient.writeData(path + "/child", "hello ZkClient");
		Object obj = zkClient.readData(path + "/child");
//		zkClient.delete(path + "/child");
	}
	
	@After
	public void test99(){
		
	}
}
